/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

/*
 * NewJDialog.java
 *
 * Created on 2011. 10. 27, �ㅽ썑 11:25:08
 */
/**
 * 
 * @author minimonk
 */
public class AndroidJDialog extends javax.swing.JDialog
{

	/** Creates new form NewJDialog */
	public AndroidJDialog(java.awt.Frame parent, boolean modal)
	{
		super(parent, modal);
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jToggleButton1 = new javax.swing.JToggleButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Path");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setLabel("Browse");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 511, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.getAccessibleContext().setAccessibleName("");

        jToggleButton1.setLabel("Start");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jButton2.setLabel("Export");

        jScrollPane1.setViewportView(jList1);

        jButton3.setText("i18n");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton3, 0, 0, Short.MAX_VALUE)
                            .addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jToggleButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 246, Short.MAX_VALUE)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

	public static List<File>	JavaFileList;	// = new List<File>();
	public static List<File>	XmlFileList;	// = new List<File>();

	public class FileUtil
	{
		private List<File> getFiles(String dirpath, FilenameFilter filter)
		{
			File dir = new File(dirpath);
			List<File> ret = new ArrayList<File>();
			for (File f : dir.listFiles())
			{
				if (f.isDirectory())
				{
					String dirpath2 = dirpath + "\\" + f.getName();
					ret.addAll(getFiles(dirpath2, filter));
				}
				else if (filter.accept(dir, f.getName()))
				{
					ret.add(f);
				}
			}
			return ret;
		}

		public void listFiles(String dir)
		{
			File directory = new File(dir);
			if (!directory.isDirectory())
			{
				System.out.println("No directory provided");
				return;
			}

			FilenameFilter filefilter_java = new FilenameFilter() {
				public boolean accept(File dir, String name)
				{ // if the file extension is .txt return true, else false
					return name.endsWith(".java");
				}
			};

			FilenameFilter filefilter_xml = new FilenameFilter() {
				public boolean accept(File dir, String name)
				{ // if the file extension is .txt return true, else false
					return name.endsWith(".xml");
				}
			};

			JavaFileList = getFiles(dir, filefilter_java);
			XmlFileList = getFiles(dir, filefilter_xml);
		}
	}

	private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt)
	{// GEN-FIRST:event_jToggleButton1ActionPerformed
		// TODO add your handling code here:
		DefaultListModel listModel = new DefaultListModel();
		
		if (jToggleButton1.isSelected())
		{
			int idx, count;
			String str = jTextField1.getText();

			// 실행전에 이전에 사용한 데이터 비우기
			AndroidBugTracker.clear();
			
			// XML 파일과 JAVA 파일을 경로에서 검색함
			FileUtil fu = new FileUtil();
			fu.listFiles(str);
		
			// XML 파일을 검색해서 uses-permission 목록을 빼내고 정렬함
			count = XmlFileList.size();
			for (idx = 0; idx < count; idx++)
			{
				AndroidBugTracker.PermissionSearcher(XmlFileList.get(idx).toString());
			}
//			System.out.println(XmlFileList);
//			System.out.println(AndroidBugTracker.XML_PermList);

			// JAVA 파일을 검색해서 XML 파일의 퍼미션과 검색함
			count = JavaFileList.size();
			for (idx = 0; idx < count; idx++)
			{
				AndroidBugTracker.antlr(JavaFileList.get(idx).getPath());
//				System.out.println(JavaFileList.get(idx).getPath());
//				System.out.println(AndroidBugTracker.managerList.size());
//				System.out.println(AndroidBugTracker.InterfaceList.size());
//				System.out.println(AndroidBugTracker.IntentList.size());
//				System.out.println("");
				
				if(	AndroidBugTracker.managerList.size() == 0 &&
					AndroidBugTracker.InterfaceList.size() == 0 &&
					AndroidBugTracker.IntentList.size() == 0) continue;
				
				listModel.addElement(JavaFileList.get(idx).getPath());	// 파일이름을 List에 추가

				System.out.println("------------------------------------------");
				System.out.println(JavaFileList.get(idx).getPath());
				System.out.println(AndroidBugTracker.InterfaceList);
				System.out.println(AndroidBugTracker.InterfuncList);				
//				System.out.println("------------------------------------------\n");
				
				AndroidBugTracker.sortAll();
					AndroidBugTracker.compare();
					AndroidBugTracker.sortRes();
					for (String name : AndroidBugTracker.ResultList)	listModel.addElement(name);

					if(AndroidBugTracker.ResultList.size() > 0 && AndroidBugTracker.ResultList.get(0).equals("    + All permissions suitable"))
					{
						// ResultList에 결과가 있지만 처음꺼가 퍼미션 문제없음일 경우 interfacelist를 추가하지 않음
						;
					}
					else
					{
						for (String name : AndroidBugTracker.InterfuncList)	listModel.addElement("    - interfaces " + name + "()");
					}
					jList1.setModel(listModel);
					
//					System.out.println("------------------------------------------");
					System.out.println(JavaFileList.get(idx).getPath());
					System.out.println(AndroidBugTracker.managerList);
					System.out.println(AndroidBugTracker.IntentList);
					System.out.println(AndroidBugTracker.InterfaceList);
					System.out.println("------------------------------------------\n");

				AndroidBugTracker.ResultList.clear();
				AndroidBugTracker.managerList.clear();
				AndroidBugTracker.InterfaceList.clear();
				AndroidBugTracker.IntentList.clear();
				AndroidBugTracker.InterfuncList.clear();				
				AndroidBugTracker.JVA_PermList.clear();
			}
			
			// Over 퍼미션 체크
//			AndroidBugTracker.compareAll();
//			for (String name : AndroidBugTracker.FullResultList)
//				listModel.addElement(name);
//			jList1.setModel(listModel);
		}
		else
		{
			jList1.setModel(new DefaultListModel());
		}
	}// GEN-LAST:event_jToggleButton1ActionPerformed

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
	{// GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		javax.swing.JFileChooser chooser = new javax.swing.JFileChooser(); // "C:\\Documents and Settings\\minimonk\\My Documents\\NetBeansProjects\\AndroidBugTracer\\src\\examples"
		chooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
		chooser.showOpenDialog(AndroidJDialog.this);
		jTextField1.setText(chooser.getSelectedFile().getPath());
	}// GEN-LAST:event_jButton1ActionPerformed

	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
	{// GEN-FIRST:event_jTextField1ActionPerformed
		// TODO add your handling code here:
	}// GEN-LAST:event_jTextField1ActionPerformed

	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
	// TODO add your handling code here:
	}//GEN-LAST:event_jButton3ActionPerformed

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[])
	{
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try
		{
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels())
			{
				if ("Nimbus".equals(info.getName()))
				{
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		}
		catch (ClassNotFoundException ex)
		{
			java.util.logging.Logger.getLogger(AndroidJDialog.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		catch (InstantiationException ex)
		{
			java.util.logging.Logger.getLogger(AndroidJDialog.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		catch (IllegalAccessException ex)
		{
			java.util.logging.Logger.getLogger(AndroidJDialog.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		catch (javax.swing.UnsupportedLookAndFeelException ex)
		{
			java.util.logging.Logger.getLogger(AndroidJDialog.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the dialog */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run()
			{
				AndroidJDialog dialog = new AndroidJDialog(
						new javax.swing.JFrame(), true);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {

					@Override
					public void windowClosing(java.awt.event.WindowEvent e)
					{
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton			jButton1;
	private javax.swing.JButton			jButton2;
    private javax.swing.JButton jButton3;
	private javax.swing.JLabel			jLabel1;
	private javax.swing.JList			jList1;
	private javax.swing.JPanel			jPanel1;
	private javax.swing.JScrollPane		jScrollPane1;
	private javax.swing.JTextField		jTextField1;
	private javax.swing.JToggleButton	jToggleButton1;
	// End of variables declaration//GEN-END:variables
}
